<template>
    <div class="container">
        <div class="content">
            <img src="@/assets/login-logo.png" alt="Logo" class="logo">
        </div>
        <div class="qr-code">
            <p class="qr-title">打开「群相册云服务」</p>
            <p class="qr-title">扫码登录</p>
            <qrcode :value="qrCodeValue" class="qr-image" :size="150" />
            <p>首页右上角点击电脑上传</p>
            <p>选择<span class="highlight">[扫一扫]</span></p>
        </div>
        <span class="ipc">闽ICP备2024056849号  福建全威信息科技有限公司</span>
    </div>
</template>

<script>
import QRCodeVue from 'qrcode.vue'
import { getRequestBody, login, checkIsLogin } from '@/utils/Account'
import { toPage } from '@/router'

export default {
    name: 'PhotoAlbum',
    components: {
        Qrcode: QRCodeVue
    },
    data() {
        return {
            qrCodeValue: '',
            checkCount: 0,
            maxChecks: 30,
            interval: null
        }
    },
    created() {
        this.qrCodeValue = this.generateRandomString(32)
        if (checkIsLogin()) {
            toPage('/')
        } else {
            this.startPolling()
        }
    },
    beforeUnmount() {
        this.stopPolling()
    },
    methods: {
        generateRandomString(length) {
            const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
            let result = ''
            const charactersLength = characters.length
            for (let i = 0; i < length; i++) {
                result += characters.charAt(Math.floor(Math.random() * charactersLength))
            }
            return result
        },
        async startPolling() {
            console.log('!!!!do start checklogin')
            this.stopPolling()
            while (this.checkCount < this.maxChecks) {
                this.checkCount++
                const startTime = Date.now()
                try {
                    const response = await this.checkLogin(this.qrCodeValue)
                    console.log(response)
                    if (response.code === 0) {
                        console.log('login success', response)
                        login(response)

                        this.stopPolling()
                        // Handle successful login
                        toPage('/')
                        return
                    }
                } catch (error) {
                    console.error(error)
                }
                const elapsed = Date.now() - startTime
                const remainingTime = 4000 - elapsed
                if (remainingTime > 0) {
                    await new Promise(resolve => setTimeout(resolve, remainingTime))
                }
            }
        },
        stopPolling() {
            if (this.interval) {
                clearInterval(this.interval)
                this.interval = null
            }
        },
        async checkLogin(token) {
            const controller = new AbortController()
            const timeoutId = setTimeout(() => controller.abort(), 10000)

            try {
                console.log(token)
                const params = {
                    token: token
                }
                const apiUrl = 'https://cloud1-3g8avjyo613a9ca1-1326935991.ap-shanghai.app.tcloudbase.com/checkLogin'
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        ...getRequestBody(),
                        ...params
                    }),
                    signal: controller.signal
                })

                clearTimeout(timeoutId)

                if (!response.ok) {
                    throw new Error('Network response was not ok')
                }

                return await response.json()
            } catch (error) {
                if (error.name === 'AbortError') {
                    console.error('Request timed out')
                } else {
                    console.error('There has been a problem with your fetch operation:', error)
                }
                return { loggedIn: false }
            }
        }
    }
}
</script>

<style scoped>
.container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    height: 100vh;
    box-sizing: border-box;
    font-family: Arial, sans-serif;
    background-color: #f0f8ff;
    position: relative;
}

.content {
    flex: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    padding-left: 50px;
}

.logo {
    width: 80%;
    max-width: 2500px;
    margin-bottom: 20px;
}

h1 {
    font-size: 36px;
    margin-bottom: 10px;
}

p {
    font-size: 18px;
    margin: 5px 0;
}

.qr-code {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    margin-right: 50px;
    height: 486px;
    width: 420px;
    border-radius: 10px;
    background: #FFF;
    box-shadow: 0 4px 35px 6px rgba(122, 122, 122, 0.10);
}

.qr-title {
    font-size: 22px;
    font-weight: bold;
}

.qr-image {
    width: 300px;
    height: 300px;
    margin: 20px 0;
}

.highlight {
    color: blue;
}

.ipc {
    position: absolute;
    bottom: 22px; /* 距离底部的距离 */
    left: 50%;
    transform: translateX(-50%);
    color: #666;
    font-size: 12px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
}
</style>
